package webview

import (
	"fmt"
	"gitee.com/snxamdf/wui/logs"
	"gitee.com/snxamdf/wui/util"
	"html/template"
)

var bindTmpl = template.Must(template.New("bindTmpl").Parse(`{{ range . }}
__go__bind__.push({"cn":"{{.CN}}", "wi":"{{.WI}}", "v":"{{.V}}"});{{ end }}
`))

var prefixJS = `
var __go__bind__ = [];`
var endJS = `
for (var i = 0; i < __go__bind__.length; i++) {
    var __bind = __go__bind__[i];
    var cn = __bind.cn;
    var wi = __bind.wi;
    var v = __bind.v;
    GoBind.bind(cn, wi, v);
}
`

type binding struct {
	//所有的待同步绑定组件数据
	bds []bd
}

type bd struct {
	CN string
	WI string
	V  interface{}
}

func (m *binding) BindingJS(widgets map[string]WidgetInterface) {
	var bds []bd
	for _, widget := range widgets {
		bds = append(bds, bd{
			CN: widget.GetComponent().GetName(),
			WI: widget.GetId(),
			V:  widget.GetValue().Object(),
		})
	}
	m.bds = bds
}

func (m *binding) EvalJS(wv WV) {
	bindJS, _ := util.HtmlTemplate(bindTmpl, m.bds)
	bindJS = fmt.Sprintf("%s%s%s", prefixJS, bindJS, endJS)
	logs.Debug("binding.BindingJS() Result:", bindJS)
	if err := wv.IEval(bindJS); err != nil {
		logs.Error(err)
	} else {
		logs.Info("go bind js success")
	}
	m.bds = nil
}
